import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFDateWidgetSchema } from '@delon/form';
import { DynamicSettingModalComponent, SearchDrawerService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { AccountDetailComponent } from 'src/app/shared/components/account-detail/account-detail.component';
import { UsermanageService } from '../../../services/usercenter.service';
import { EditPartnerComponentsAddComponent } from './editPartner/editPartner.component';
import { EditSaleComponentsAddComponent } from './editSale/editSale.component';
import { ShowServiceComponent } from './showService/showservice.component';
@Component({
  selector: 'app-Freight-components-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../../commom/less/commom-table.less']
})
export class FreightComponentsListComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];

  @ViewChild('promoterModal', { static: false })
  promoterModal!: any;
  promotersTelephone = '';

  loadingList = true;

  constructor(
    public service: UsermanageService,
    private modal: NzModalService,
    private router: Router,
    private ar: ActivatedRoute,
    public shipperservice: ShipperBaseService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
    this.sfValue = { enterpriseName: '', contactName: '' };
  }

  ngOnInit() {
    this.initSF();
    this.initST();
  }

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { listSource: 1 });
    if (this.sfValue) {
      Object.assign(requestOptions.body, {
        ...this.sfValue
      });
      if (this.sfValue.createTime) {
        Object.assign(requestOptions.body, {
          createTime: {
            start: this.sfValue.createTime[0],
            end: this.sfValue.createTime[1]
          }
        });
      }
      if (this.sfValue.approvalTime) {
        Object.assign(requestOptions.body, {
          approvalTime: {
            start: this.sfValue.approvalTime[0],
            end: this.sfValue.approvalTime[1]
          }
        });
      }
    }
    this.loadingList = true;
    return requestOptions;
  };

  dataProcess = (data: STData[]): STData[] => {
    this.loadingList = false;
    return data;
  };

  settingAction(item?: any) {
    this.modal.create({
      nzTitle: '基础设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '2',
        businessId: item.id
      },
      nzFooter: null
    });
  }

  showAccountDetail(item: any) {
    this.modal.create({
      nzTitle: '资金账户',
      nzContent: AccountDetailComponent,
      nzNoAnimation: true,
      nzWidth: 600,
      nzComponentParams: {
        isCanCreate: true,
        url: '/api/fcc/accountBalance/getShipperAccountDetailByOperator',
        params: {
          accountType: 1,
          roleId: item.id,
          ctfId: item.unifiedSocialCreditCode,
          clientName: item.enterpriseName,
          projectId: item.mainProjectId,
          ltdId: item.networkTransporter
        }
      },
      nzFooter: null
    });
  }
  showService(record: any) {
    const modalRef = this.modal.create({
      nzTitle: '分配客服人员',
      nzContent: ShowServiceComponent,
      nzWidth: 600,
      nzComponentParams: {
        i: record
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  editPartner(record?: any) {
    let status = 1;
    if (record) {
      status = 2;
    }
    if (this.selectedRows.length <= 0 && !record) {
      this.service.msgSrv.error('请选择订单！');
      return;
    }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    const modalRef = this.modal.create({
      nzTitle: '修改合伙人',
      nzContent: EditPartnerComponentsAddComponent,
      nzWidth: 800,
      nzComponentParams: {
        i: record,
        sts: status,
        rows: params
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  editSale(record?: any) {
    let status = 1;
    if (record) {
      status = 2;
    }
    if (this.selectedRows.length <= 0 && !record) {
      this.service.msgSrv.error('请选择订单！');
      return;
    }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    const modalRef = this.modal.create({
      nzTitle: '修改渠道销售',
      nzContent: EditSaleComponentsAddComponent,
      nzWidth: 800,
      nzComponentParams: {
        i: record,
        sts: status,
        rows: params
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      if (res) {
        this.st.load(1);
      }
    });
  }
  initSF() {
    this.schema = {
      properties: {
        enterpriseName: {
          title: '企业名称',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        contactName: {
          title: '管理员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        enterpriseType: {
          type: 'string',
          title: '企业类型',
          enum: [
            { label: '全部', value: '' },
            { label: '物流企业', value: 1 },
            { label: '货运代理', value: 2 },
            { label: '生产型企业', value: 3 },
            { label: '贸易类企业', value: 4 },
            { label: '科技型企业', value: 5 },
            { label: '化学化工企业', value: 6 },
            { label: '其他', value: 7 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        enterpriseAddressCode: {
          type: 'string',
          title: '公司所在地',
          enum: [{ label: '全部', value: '' }],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        oftenUsedServices: {
          type: 'string',
          title: '常用服务',
          enum: [
            { label: '全部', value: '' },
            { label: '整车发货', value: 10 },
            { label: '大宗发货', value: 20 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        customerType: {
          type: 'string',
          title: '客户类型',
          enum: [
            { label: '全部', value: '' },
            { label: '直客', value: 1 },
            { label: '渠道客户', value: 20 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        channelName: {
          title: '业务员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        partnerNamee: {
          title: '合伙人',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        customerServiceId: {
          title: '客服人员',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        approvalUserName: {
          title: '审核人',
          type: 'string',
          ui: {
            placeholder: '请输入',
            showRequired: false
          }
        },
        createTime: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd HH:mm:ss',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        approvalTime: {
          title: '审核时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd HH:mm:ss',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        lockedStatus: {
          type: 'string',
          title: '企业状态',
          enum: [
            { label: '全部', value: '' },
            { label: '正常', value: 0 },
            { label: '冻结', value: 1 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        source: {
          type: 'string',
          title: '注册渠道',
          enum: [
            { label: '全部', value: '' },
            { label: '货主注册', value: 1 },
            { label: '平台添加', value: 2 },
            { label: '数据迁移', value: 4 }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        isExpired: {
          type: 'string',
          title: '证件是否过期',
          enum: [
            { label: '全部', value: '' },
            { label: '是', value: true },
            { label: '否', value: false }
          ],
          default: '',
          ui: {
            widget: 'select'
          }
        },
        networkTransporter: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        }
      }
    };
  }

  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      {
        title: '企业名称',
        index: 'enterpriseName',
        width: 250,
        type: 'link',
        click: item => this.router.navigate(['./detail', item.id], { relativeTo: this.ar })
      },
      { title: '企业评分', className: 'text-center', render: 'score', width: 160 },
      {
        title: '公司所在地',
        index: 'province',
        width: 200,
        format: item => `${item.provinceName ? item.provinceName: ''}${item.cityName ? item.cityName: ''}${item.areaName ? item.areaName: ''}`
      },
      { title: '管理员', render: 'contacter', width: 200 },
      { title: '统一社会信用代码', className: 'text-center', render: 'unifiedSocialCreditCode', width: 200 },
      {
        title: '企业类型',
        className: 'text-center',
        index: 'enterpriseType',
        width: 160,
        type: 'enum',
        enum: { 1: '物流企业', 2: '货运代理', 3: '生产型企业', 4: '贸易类企业', 5: '科技型企业', 6: '化学化工企业', 7: '其他' }
      },

      {
        title: '常用服务',
        className: 'text-center',
        index: 'oftenUsedServices',
        type: 'enum',
        enum: { 10: '整车发货', 20: '大宗发货' },
        width: 140
      },
      { title: '渠道销售', className: 'text-center', render: 'promotersTelephone', width: 200 },
      { title: '合伙人', className: 'text-center', render: 'partnerName', width: 200 },
      { title: '客服人员', className: 'text-center', render: 'customerServiceIdLabel', width: 200 },
      { title: '网络货运人', className: 'text-center', index: 'netTranName', width: 180 },
      {
        title: '注册渠道',
        className: 'text-center',
        index: 'source',
        type: 'enum',
        enum: { 1: '货主注册', 2: '平台添加', 3: '运营添加', 4: '数据迁移' },
        width: 130
      },
      { title: '申请时间', className: 'text-center', index: 'createTime', width: 180, type: 'date' },
      { title: '审核时间', className: 'text-center', index: 'approvalTime', width: 180, type: 'date' },
      { title: '迁移认证时间', className: 'text-center', index: 'transferApprovalTime', width: 180, type: 'date' },
      { title: '审核人', className: 'text-center', index: 'approvalUserName', width: 130 },
      {
        title: '保险认证状态',
        className: 'text-center',
        index: 'insuranceAuthState',
        type: 'badge',
        badge: {
          10: { text: '成功', color: 'success' },
          20: { text: '失败', color: 'error' }
        },
        width: 130
      },
      {
        title: '企业状态',
        className: 'text-center',
        index: 'lockedStatus',
        type: 'badge',
        badge: {
          0: { text: '正常', color: 'success' },
          1: { text: '冻结', color: 'error' }
        },
        width: 130
      },
      {
        title: '操作',
        width: '220px',
        className: 'text-left options',
        fixed: 'right',
        buttons: [
          // {
          //   text: '查看',
          //   acl: { ability: ['USERCENTER-FREIGHT-LIST-view'] },
          //   click: item => {
          //     this.router.navigate(['./detail', item.id], { relativeTo: this.ar });
          //     // this.router.navigate(['./view', item.id], { relativeTo: this.ar, queryParams: { tenantId: item.tenantId } });
          //   }
          // },
          // {
          //   acl: { ability: ['USERCENTER-FREIGHT-LIST-basicSetting'] },
          //   text: '基础设置',
          //   click: item => this.settingAction(item)
          // },
          { type: 'divider' },
          {
            acl: { ability: ['USERCENTER-FREIGHT-LIST-balance'] },
            text: '资金账户',
            click: item => this.showAccountDetail(item)
          },
          {
            text: '分配客服<br>',
            click: item => this.showService(item)
          },
          {
            text: '修改合伙人',
            click: item => this.editPartner(item)
          },
          {
            text: '修改渠道销售',
            click: item => this.editSale(item)
          }
        ]
      }
    ];
  }
  daoyun(item: any) {
    this.router.navigate(['./view', item.tenantId], { relativeTo: this.ar });
  }

  addPromoter(item?: any) {
    this.promotersTelephone = item?.promotersTelephone;
    const modal = this.modal.create({
      nzTitle: '推广业务员',
      nzContent: this.promoterModal,
      nzOnOk: () => {
        if (!!!this.promotersTelephone) {
          return false;
        }
        if (typeof this.promotersTelephone === 'string' && !/(^1\d{10}$)/.test(this.promotersTelephone)) {
          this.service.msgSrv.error('手机格式错误');
          return false;
        }
        this.service.request(this.service.$api_add_salesman, { ids: [item.id], salesmanMobile: this.promotersTelephone }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success(item?.promotersTelephone ? '添加推广员成功' : '修改推广员成功');
          }
          this.st.load();
        });
        return;
      }
    });
  }

  creat() {
    this.router.navigate(['./new'], { relativeTo: this.ar });
  }

  exportList() {
    const params = { listSource: 1, pageSize: -1 };
    if (this.sf) {
      Object.assign(params, {
        ...this.sfValue
      });
    }
    this.service.downloadFile(this.service.$api_export_enterprise, params);
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this.st.reload();
  }
}
